import type { AsyncComponentLoader, Component } from 'vue'
import { createApp } from 'vue'

import AsyncLoading from '@/components/asyn-Loading/index.vue'
/**
 * 动态注册组件
 * @description 描述信息
 * @remarks 备注
 * @param {*String}  []
 * @returns {*Object}
 */
export function componentInstall<T>(key: string, node: T) {
  if (!window.$vue.component(key) && node) {
    window.$vue.component(key, node)
    // window.$vue.component(key, componentLoadAsync(node as any));
  }
}

/**
 * 异步加载组件
 * @description 描述信息
 * @remarks 备注
 * @param {*String}  []
 * @returns {*Object}
 */
export function componentLoadAsync<T extends Component>(loader: AsyncComponentLoader<any>, isLoading = false) {
  return defineAsyncComponent<T>({
    loader,
    loadingComponent: isLoading ? AsyncLoading : undefined,
    delay: 200,
  })
}

interface ComponentToHtmlProps {
  style?: string
  title?: string
  class?: string
}
/**
 * 组件转HTML
 * @description 描述信息
 * @remarks 备注
 * @param {*String}  []
 * @returns {*Object}
 */
export function componentToHtml<T>(component: Component, props?: T & ComponentToHtmlProps) {
  const dom = document.createDocumentFragment()
  const app = createApp(component, props as any).mount(
    dom as unknown as Element,
  )
  return {
    el: (app.$el as HTMLElement).cloneNode(true) as HTMLElement,
    app,
  }
}
